Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
解法:
這題可以很簡單的使用 reverse! 解決, 但是這邊挑戰不使用 reverse 該如何解
缺點是會佔用到比較多額外空間
def reverse_string(s)
len = s.length
arr = []
while len > 0
arr << s.pop
len -= 1
end
arr
end
若是陣列長度為奇數,兩邊陣列位置相等表示已交換完成,若陣列長度是偶數,左右數值不會相遇在同一位址,因此當左邊陣列位址將大於右邊陣列位址表示交換完畢。
def reverse_string(s)
left = 0
right = s.length - 1
while left < right
t = s[left]
s[left] = s[right]
s[right] = t
left += 1
right -= 1
end
s
end